import 'package:flutter/material.dart';
import 'package:demo_day_1/models/repository.dart';
import 'package:demo_day_1/models/user.dart';
import 'package:demo_day_1/services/gitcode_service.dart';

class HomeScreen extends StatefulWidget {
  const HomeScreen({Key? key}) : super(key: key);

  @override
  State<HomeScreen> createState() => _HomeScreenState();
}

class _HomeScreenState extends State<HomeScreen> {
  final GitcodeService _gitcodeService = GitcodeService();
  late Future<List<Repository>> _repositoriesFuture;
  late Future<User> _currentUserFuture; // 用于显示当前登录用户信息

  @override
  void initState() {
    super.initState();
    _currentUserFuture = _gitcodeService.getCurrentUser();
    _repositoriesFuture = _gitcodeService.getCurrentUserRepositories();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('Gitcode 首页'),
        actions: [
          FutureBuilder<User>(
            future: _currentUserFuture,
            builder: (context, snapshot) {
              if (snapshot.connectionState == ConnectionState.waiting) {
                return const Center(
                    child: CircularProgressIndicator(color: Colors.white));
              } else if (snapshot.hasError) {
                return const Padding(
                  padding: EdgeInsets.symmetric(horizontal: 16.0),
                  child: Icon(Icons.error, color: Colors.red),
                );
              } else if (snapshot.hasData) {
                return Padding(
                  padding: const EdgeInsets.symmetric(horizontal: 16.0),
                  child: Row(
                    children: [
                      CircleAvatar(
                        radius: 15,
                        backgroundImage: NetworkImage(snapshot.data!.avatarUrl),
                      ),
                      const SizedBox(width: 8),
                      Text(snapshot.data!.login,
                          style: const TextStyle(fontSize: 16)),
                    ],
                  ),
                );
              }
              return const SizedBox.shrink();
            },
          ),
          IconButton(
            icon: const Icon(Icons.logout),
            onPressed: () {
              // TODO: 实现登出功能 (清除 token，返回登录页)
              ScaffoldMessenger.of(context).showSnackBar(
                const SnackBar(content: Text('登出功能待实现')),
              );
            },
          ),
        ],
      ),
      body: FutureBuilder<List<Repository>>(
        future: _repositoriesFuture,
        builder: (context, snapshot) {
          if (snapshot.connectionState == ConnectionState.waiting) {
            return const Center(child: CircularProgressIndicator());
          } else if (snapshot.hasError) {
            return Center(child: Text('加载仓库失败: ${snapshot.error}'));
          } else if (!snapshot.hasData || snapshot.data!.isEmpty) {
            return const Center(child: Text('没有找到任何仓库。'));
          } else {
            return ListView.builder(
              itemCount: snapshot.data!.length,
              itemBuilder: (context, index) {
                Repository repo = snapshot.data![index];
                return Card(
                  margin: const EdgeInsets.all(8.0),
                  child: ListTile(
                    leading: const Icon(Icons.folder),
                    title: Text(repo.name,
                        style: const TextStyle(fontWeight: FontWeight.bold)),
                    subtitle: Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        if (repo.description != null &&
                            repo.description!.isNotEmpty)
                          Text(repo.description!),
                        Text('所有者: ${repo.owner.login}'),
                      ],
                    ),
                    onTap: () {
                      // TODO: 可以导航到仓库详情页
                      ScaffoldMessenger.of(context).showSnackBar(
                        SnackBar(content: Text('点击了仓库: ${repo.name}')),
                      );
                    },
                  ),
                );
              },
            );
          }
        },
      ),
    );
  }
}
